<!DOCTYPE html>
<html>

<head>
  <title>Upload</title>
  <link rel="icon" type="image/png" href="/favicon.ico" sizes="32x32">
  <link rel='stylesheet' href='/stylesheets/style.css' />
  <script src="/javascripts/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/spark-md5/3.0.0/spark-md5.min.js"></script>
  <style type="text/css">
    .container {
      display: flex;
    }
  </style>

</head>

<body>

  <h1>Upload</h1>

  <div class="container">
    <input type="file" id="upload_file">
    <input type="button" value="上传" class="upload_btn">
  </div>
  <script nonce="TmV2ZXIgZ29pb2mc2gdG8gZ2l2ZSB5b3UgdXA=">
    let chunkSize = 1024 * 1024;// 1M
    let oUploadFile = document.querySelector('#upload_file');
    let oUploadBtn = document.querySelector('.upload_btn');
    oUploadBtn.addEventListener('click', ()=>upload(0));
    function upload(index) {
      let file = oUploadFile.files[0];

      const fName = file.name.replace(/\.\w+$/, '');
      const fExt = file.name.match(/\.\w+$/)[0];
      let start = index * chunkSize;
      if (start > file.size) {
        axios.post('/upload/merge', {
          md5: SparkMD5.hash(file.name),
          name: file.name
        }).then(res => {
          console.log('merge', res);
        })
        return;
      };
      let blob = file.slice(start, start + chunkSize);
      let blobName = `${SparkMD5.hash(file.name)}_-_${index}_-_${fName}${fExt}`;
      let blobFile = new File([blob], blobName);

      console.log('blobFile: ', blobFile);
      let formData = new FormData();
      formData.append('file', blobFile);
      formData.append('md5', SparkMD5.hash(file.name));
      formData.append('index', index);
      axios.post('/upload/slices', formData).then(res => {
        console.log(res);
        upload(++index);
      })
    }
  </script>

  <!-- ************ -->

  <form action="/upload" enctype="multipart/form-data" method="post">
    <div class="form-group">
      <input type="file" class="form-control-file" name="uploaded_file">
      <!-- <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers"> -->
      <input type="submit" value="Get me the stats!" class="btn btn-default">
    </div>
  </form>

</body>

</html>